<!--
 * @Author: WeijianXu weijian.xu@unidt.com
 * @Date: 2024-04-28 15:28:14
 * @LastEditors: WeijianXu weijian.xu@unidt.com
 * @LastEditTime: 2024-04-29 16:15:03
 * @FilePath: \echarts5-test\src\App.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup>
import { ref, onMounted } from 'vue';

const option = {
  title: {
    text: '饼图程序调用高亮示例',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b} : {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
  },
  series: [
    {
      name: '访问来源',
      type: 'pie',
      radius: '55%',
      center: ['50%', '60%'],
      data: [
        { value: 335, name: '直接访问' },
        { value: 310, name: '邮件营销' },
        { value: 234, name: '联盟广告' },
        { value: 135, name: '视频广告' },
        { value: 1548, name: '搜索引擎' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};

const echartRef = ref(null);

function downplay(myChart, index) {
  // 取消之前高亮的图形
  myChart.dispatchAction({
    type: 'downplay',
    seriesIndex: 0,
    dataIndex: index
  });
}

function dispatchAction(myChart, index, nextIndex) {
  var dataLen = option.series[0].data.length;
  downplay(myChart, index);

  const next = nextIndex % dataLen || (index + 1) % dataLen;
  // 高亮当前图形
  myChart.dispatchAction({
    type: 'highlight',
    seriesIndex: 0,
    dataIndex: next
  });
  // 显示 tooltip
  myChart.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: next
  });
}

let currentIndex = ref(-1);
function actionTimer(myChart) {
  return setInterval(() => {
    dispatchAction(myChart, currentIndex.value);
    currentIndex.value += 1;
  }, 1000);
}
onMounted(() => {
  const myChart = echartRef.value.getInstance();
  let timer = actionTimer(myChart);

  myChart.on('mouseover', () => {
    // 暂停定时器
    if (timer) {
      clearInterval(timer);
      timer = null;
      downplay(myChart, currentIndex.value);
    }
  });
  myChart.on('mouseout', () => {
    // 恢复定时器
    if (!timer) {
      downplay(myChart, currentIndex.value);
      currentIndex.value = -1;
      timer = actionTimer(myChart);
    }
  });
});
</script>

<template>
  <echart ref="echartRef" :option="option"></echart>
</template>
